package com.glxy.controller;

import com.glxy.pojo.User;
import com.glxy.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    private static User user = null;
    LoginServiceImpl loginService = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String action = request.getParameter("action");

        System.out.println(action);

        if (action.equals("login")) {
            if (user == null) user = new User();
            if (loginService == null) loginService = new LoginServiceImpl();

            user.setUserCode(request.getParameter("username"));

            user.setUserPassword(request.getParameter("password"));

            Long id = loginService.MatchUser(user.getUserCode(), user.getUserPassword());
            if (id == -2) {
                System.out.println("没有找到用户");
            } else if (id == -1) {
                System.out.println("密码错误");
            } else {
                System.out.println("登录成功");

                user.setId(id);

                session.setAttribute("user", user);
                request.getRequestDispatcher("welcome.jsp").forward(request, response);
            }
        }else if (action.equals("password")) {
            String password = user.getUserPassword();
            String oldPassword = request.getParameter("oldPassword");
            String newPassword = request.getParameter("newPassword");
            String reNewPassword = request.getParameter("reNewPassword");

            if (password.equals(oldPassword)){
                if (newPassword.equals(reNewPassword)){
                    user.setUserPassword(newPassword);
                    loginService.newPassword(user);
                    System.out.println("更改成功");
                }else {
                    System.out.println("两次新密码不一致");
                }
            }else{
                System.out.println("旧密码不正确");
            }

            request.getRequestDispatcher("password.jsp").forward(request, response);

        }else if (action.equals("exit")){
            user = null;
            loginService = null;

            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
}